import 'dart:convert';

import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

final TextEditingController _accountController = new TextEditingController();
final TextEditingController _passwordController = new TextEditingController();
var selectItemValue;

//主界面
class ChangeInfo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return OKToast(
      child: MaterialApp(
        title: 'ChangeInfo',
        home: Scaffold(
          appBar: AppBar(
            title: Text('ChangeInfo'),
          ),
          body: new Column(
            children: <Widget>[
              new UserNameInput(),
              new PasswordInput(),
              new NetWorkSelect(),
              new Login(),
            ],
          ),
        ),
      ),
    );
  }
}

//用户名
class UserNameInput extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
        child: new Row(
      children: <Widget>[
        new Container(
          child: Text(
            '账户',
            style: TextStyle(
              fontSize: 24.0,
            ),
          ),
          padding: const EdgeInsets.all(20.0),
        ),
        new Container(
          width: 200.0,
          child: TextField(
            controller: _accountController,
            decoration:
                InputDecoration(hintText: '请输入您的账户', labelText: 'Account'),
            style: TextStyle(fontSize: 16.0),
          ),
        )
      ],
    ));
  }
}

//密码
class PasswordInput extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
        child: new Row(
      children: <Widget>[
        new Container(
          child: Text(
            '密码',
            style: TextStyle(
              fontSize: 24.0,
            ),
          ),
          padding: const EdgeInsets.all(20.0),
        ),
        new Container(
          width: 200.0,
          child: TextField(
            controller: _passwordController,
            obscureText: true,
            decoration:
                InputDecoration(hintText: '请输入您的密码', labelText: 'Password'),
            style: TextStyle(fontSize: 16.0),
          ),
        )
      ],
    ));
  }
}

//下拉菜单列表
List<DropdownMenuItem> listData() {
  List<DropdownMenuItem> items = List();
  DropdownMenuItem dropdownMenuItem1 = DropdownMenuItem(
    child: Text(
      '校园网',
    ),
    value: '',
  );
  items.add(dropdownMenuItem1);
  DropdownMenuItem dropdownMenuItem2 = DropdownMenuItem(
    child: Text(
      '中国移动',
    ),
    value: 'cmcc',
  );
  items.add(dropdownMenuItem2);
  DropdownMenuItem dropdownMenuItem3 = DropdownMenuItem(
    child: Text(
      '中国联通',
    ),
    value: 'unicom',
  );
  items.add(dropdownMenuItem3);
  DropdownMenuItem dropdownMenuItem4 = DropdownMenuItem(
    child: Text(
      '中国电信',
    ),
    value: 'telecom',
  );
  items.add(dropdownMenuItem4);
  return items;
}

//下拉菜单组件
class NetWorkSelect extends StatefulWidget {
  @override
  _NetWorkSelectState createState() => _NetWorkSelectState();
}

class _NetWorkSelectState extends State<NetWorkSelect> {
  void changeMethod(var T) {
    setState(() {
      selectItemValue = T;
    });
  }

  Widget build(BuildContext context) {
    return DropdownButton(
      items: listData(),
      hint: Text(
        '请选择运营商',
      ),
      onChanged: (T) {
        changeMethod(T);
      },
      value: selectItemValue,
      elevation: 24,
      style: TextStyle(color: Colors.red),
      isExpanded: true,
      iconSize: 50.0,
    );
  }
}

//
class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: RaisedButton(
        onPressed: () {
          save();
          loginMethod();
        },
        child: Text(
          '登录',
        ),
      ),
    );
  }

  var account = _accountController.text;
  var password = _passwordController.text;
  var network = selectItemValue;

//sharePreferences方法保存到本地
  void save() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString('account', account);
    sharedPreferences.setString('password', password);
    sharedPreferences.setString('network', network);
  }
}

//登录方法
void loginMethod() async {
  var connectivityResult = await (Connectivity().checkConnectivity());
  if (connectivityResult == ConnectivityResult.mobile) {
    showToast("请连接校园网WIFI！");
  } else {
    var wifiName = await (Connectivity().getWifiName());
    var wifiBBISD = await (Connectivity().getWifiBSSID());
    var wifiIP = await (Connectivity().getWifiIP());
    print(wifiName);
    print(wifiBBISD);
    print(wifiIP);
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    var account = await sharedPreferences.get('account');
    var password = await sharedPreferences.get('password');
    var network = await sharedPreferences.get('network');
    if (account == null ||
        password == null ||
        account == '' ||
        password == '') {
      showToast('请先输入账户信息！');
    }
    if (network != null) {
      network = '%40' + network;
    } else {
      network = '';
    }
    var url =
        'http://10.2.5.251:801/eportal/?c=Portal&a=login&login_method=1&user_account=' +
            account +
            network +
            '&user_password=' +
            password;

    print(url);
    Response response = await Dio().get(url);
    print(response.data);
    var data = response.data.toString();
    data = data.substring(1, data.length - 1);
    var jsonData = jsonDecode(data);
    var retCode = jsonData['ret_code'];
    var result = jsonData['result'];
    if (result == '1') {
      showToast("登录成功！");
    } else {
      switch (retCode) {
        case '1':
          showToast("账户密码不对！");
          break;
        case '2':
          showToast("IP已在线！");
          break;
        case '3':
          showToast("系统忙！");
          break;
        case '4':
          showToast("未知错误！");
          break;
        case '5':
          showToast("REQ_CHALLENGE失败！");
          break;
        case '6':
          showToast("REQ_CHALLENGE超时！");
          break;
        case '7':
          showToast("认证失败！");
          break;
        case '8':
          showToast("认证超时！");
          break;
        case '9':
          showToast("下线失败！");
          break;
        case '10':
          showToast("下线超时！");
          break;
        case '11':
          showToast("其他错误！");
          break;
      }
    }
  }
}
